package com.bodacn.packapp;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;




/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentC extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    public static final int msgFocusBarcode = 1001;
    public static final int msgTypeInit=1002;
    public static final int msgRESULTINFO=1003;
    public static final int msgERRINFO=1004;
    private static final int MSG_ERROR=9005;
    //全局变量
    Toast curToast;
    String curDepart,curDepartNo,curLoginUserNo,curLoginUser,curServiceUrl="",curTermNo="00000",curServiceDir,CPUID;
    String PrBarcode;
    Button btn_Find,btn_Sync;
    ListView detailList;
    TextView txt_hintinfo;
    ImageButton btn_EditBarcode;
    EditText edt_barcode;
    JSONArray detailJSON,resultJSON;
    private EditText editA_startDate, editA_endDate;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentC() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerC(new MainActivity.OnTransParamsListenerC() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d("FragmentC","LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            curTermNo=mParams.get("TermNo").toString();
                            Log.d("FragmentC","LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.sendMessage(msg);

                        }
                        if ((paramComm=="Barcode")){
                            String barcode=mParams.get("Barcode").toString();
                            edt_barcode.setText(barcode);
                            scanBarcode(barcode);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_c, container, false);
        InitView(root);
        System.out.println("fragment_a_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        detailList=(ListView) view.findViewById(R.id.detailList);
        detailList.setOnItemClickListener(this);
        detailList.setFocusable(false);
        detailList.setFocusableInTouchMode(false);
        btn_Find=(Button)view.findViewById(R.id.btn_Find);
        btn_Find.setOnClickListener(this);
        btn_Find.setFocusable(false);
        btn_Find.setFocusableInTouchMode(false);
        btn_Sync=(Button)view.findViewById(R.id.btn_Sync);
        btn_Sync.setOnClickListener(this);
        btn_Sync.setFocusable(false);
        btn_Sync.setFocusableInTouchMode(false);
        btn_EditBarcode=(ImageButton)view.findViewById(R.id.btn_EditBarcode);
        btn_EditBarcode.setOnClickListener(this);
        btn_EditBarcode.setFocusable(false);
        btn_EditBarcode.setFocusableInTouchMode(false);
        txt_hintinfo=(TextView)view.findViewById(R.id.txt_hintinfo);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }

                        ExecScanBarcode(v);

                    }

                }
                return false;
            }
        });
        edt_barcode.setFocusable(true);
        edt_barcode.setFocusableInTouchMode(true);
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }

    private void ExecScanBarcode(View v)
    {
        playRingtone();
        //隐藏键盘
        edt_barcode.setInputType(InputType.TYPE_NULL);
        hideIM(v);
        if (edt_barcode.getText().toString().length()==0) {
            curToast.setText("请先输入条码!");
            curToast.show();
            return;
        } else {
            PrBarcode = edt_barcode.getText().toString();
            scanBarcode(edt_barcode.getText().toString());
            if (edt_barcode != null) {
                edt_barcode.selectAll();
                edt_barcode.setFocusable(true);
                edt_barcode.setFocusableInTouchMode(true);
                edt_barcode.requestFocus();
                edt_barcode.requestFocusFromTouch();
            }
        }
    }

    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getContext(), notification);
        r.play();

    }
    //正式扫描;
    private void scanBarcode(String paramBarcode)
    {
        try {
            detailJSON=new JSONArray("[]");
            //清除界面显示内容;
            final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
            detailList.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_InitInfoQuery @TermNo='"+curTermNo+"',@BarCode='"+paramBarcode+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_Find:
                ExecScanBarcode(v);
                break;
            case R.id.btn_EditBarcode:
                System.out.println("onClick btn_EditBarcode");
                edt_barcode.setInputType(InputType.TYPE_CLASS_NUMBER);
                edt_barcode.setFocusable(true);
                edt_barcode.setFocusableInTouchMode(true);
                edt_barcode.requestFocus();
                edt_barcode.requestFocusFromTouch();
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_Sync:
                if (edt_barcode.getText().toString().length()==0) {
                    curToast.setText("请先输入条码!");
                    curToast.show();
                    return;
                } else {
                    SyncData(edt_barcode.getText().toString());
                }
                break;
            default:
                break;
        }
    }

    //同步数据;
    private void SyncData(String paramBarcode)
    {
        //执行SQL过程
        String SqlComm= "Exec KeyPoint_Pack_SyncSZBarcode @Barcode='"+paramBarcode+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ERROR:
                        Bundle bundle1=msg.getData();
                        curToast.setText(bundle1.getString("HintInfo"));
                        curToast.show();
                        break;
                    case msgFocusBarcode:
                        //设置焦点
                        System.out.println("FragmentA 设置焦点-------------------------------1.Start");
                        if (edt_barcode!=null) {
                            edt_barcode.setText("");
                            edt_barcode.selectAll();
                            edt_barcode.setFocusable(true);
                            edt_barcode.setFocusableInTouchMode(true);
                            edt_barcode.requestFocus();
                            edt_barcode.requestFocusFromTouch();
                        }
                        System.out.println("FragmentA 设置焦点-------------------------------1.End");
                        break;
                    case msgTypeInit:
                        //显示预排单;
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        detailList.setAdapter(detailListAdapter);
                        break;
                    case msgRESULTINFO:
                        try {
                            txt_hintinfo.setText(resultJSON.optJSONObject(0).getString("RESULTINFO"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        txt_hintinfo.setTextColor(getResources().getColor(R.color.blue));
                        break;
                    case msgERRINFO:
                        try {
                            txt_hintinfo.setText(resultJSON.getJSONObject(0).getString("ERRINFO"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        txt_hintinfo.setTextColor(getResources().getColor(R.color.red));
                        MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(),R.raw.warn);
                        mediaPlayer.start();
                        AlertDialog alertDialog = null; // 创建对话框
                        try {
                            alertDialog = new AlertDialog.Builder(getActivity())
                                    .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ERRINFO"))
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        alertDialog.show(); // 显示对话框
                        break;
                    default:
                        break;
                }
            }
        }
    };

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public  void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    Message msg = new Message();
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("TypeInit")==true) {
                            detailJSON = jsonArray;
                            msg.what = msgTypeInit;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("RESULTINFO")==true) {
                            resultJSON = jsonArray;
                            msg.what = msgRESULTINFO;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);

                        }
                        if (jsonArray.optJSONObject(0).has("ERRINFO")==true) {
                            resultJSON = jsonArray;
                            msg.what = msgERRINFO;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);

                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                }
            }

        };
        new Thread(run).start();

    }



    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_c_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(50)));
            int color = getResources().getColor(R.color.text_blue);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_BarCode);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("BarCode").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_OrderNo);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_StyleNo);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_StyleSort);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("StyleSort").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_CustColor);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("CustColor").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_CustSize);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("CustSize").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_SewSize);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("SewSize").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_LastUpdateTime);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("LastUpdateTime").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_SaveTime);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("SaveTime").toString());
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }
    //清除界面显示内容
    private void clearFormText(){


    }


    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println("FragmentC 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.setText("");
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
        }
        System.out.println("FragmentC 设置焦点-------------------------------1.End");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}
